package com.bee.beemanage.api.controller.common;

import com.bee.beemanage.system.common.utils.files.OSSUtil;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;

import static com.bee.beemanage.system.common.utils.result.ResultTool.fail;
import static com.bee.beemanage.system.common.utils.result.ResultTool.success;

@RestController
@RequestMapping("/bee-manage/file")
@Api(value ="文件上传下载相关接口",tags = "文件上传下载相关接口")
public class FileController {
    @Resource
    private OSSUtil ossUtil;

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/upload")
//    @PreAuthorize("hasAnyAuthority('sys:file:uploadFile')")
    private Result uploadFile(MultipartFile file){
        Result result;
        // 最后上传生成的文件名
        String finalFileName = System.currentTimeMillis() + String.valueOf(new SecureRandom().nextInt(0x0400)) + ".jpg";
        // 上传oss
        try {
            ossUtil.uploadFile2OSS(file.getInputStream(), finalFileName);
        } catch (IOException e) {
            result = fail(ResultCode.FILE_UPLOAD_FAIL);
            return result;
        }
        //获取文件的URl地址
        String imgUrl = ossUtil.getImgUrl(finalFileName);
        HashMap<String,String> resultMap = new HashMap<>();
        resultMap.put("imgUrl",imgUrl);
        return success(resultMap);
    }

    @ApiOperation(value = "文件删除", notes = "文件删除")
    @PostMapping("/deleteFile")
//    @PreAuthorize("hasAnyAuthority('sys:file:deleteFile')")
    private Result deleteFile(@RequestBody String url){
        ossUtil.deleteFile(url);
        return success();
    }
}
